/**
 * Created by hjqi on 2016/3/3.
 */

/*
    require 3-party lib
 */
var express = require('express');
var router = express.Router();
/*var libK8s = require('../lib/k8s/kubernetes');
var _k8s = new libK8s();*/
var _k8s_adp = require('../lib/k8s/k8sAdpter');
//compose not in product env, so use default cluster
//var _k8s = _k8s_adp.getK8s();

/*
    init require object
*/

var composeMetaInfoDB = require('../db/composeMetaInfoDB');
var compMetaInfoDB = new composeMetaInfoDB();

var libUserAcc = require('../lib/user/userAccount');
var _userAcc  = new libUserAcc();
var _getlimitsTotal = require('../lib/common/common').getLimitsFromCompose;
var _getlimitsUpdate = require('../lib/common/common').getLimitsFromComposeUpt;
var _getlimitsRelease = require('../lib/common/common').getLimitsFromComposeForRelease;


//compose part
router.post('/createComp',function(req, res, next){
    var _data =  req.body;
    var _username = req.username;

    var _limits = _getlimitsTotal(_data.services);
    _userAcc.checkAccountBalance(_username,_limits).then(function(){

        return _k8s_adp.getK8s('default');
        //return _k8s.createCompose(_username,_data);
    }).then(function(_k8s){
        return _k8s.createCompose(_username,_data);
    }).then(function(){
        return _userAcc.requestResourceUpdate(_username,_limits);
    }).then(function(){
        res.send(true);
    }).catch(function(err){
        res.status(400);
        res.send(err.message);
    });
});

router.post('/deleteComp',function(req, res, next){
    var _data =  req.body;
    var _username = req.username;

    var _limits = undefined;
    _k8s_adp.getK8s('default').then(function(_k8s){
        return _k8s.getServiceFromCompId(_username,_data.id);
    })
    .then(function(services) {
        _data.services = services;
        return _k8s.deleteCompose(_username, _data);
    }).then(function(){
        _limits = _getlimitsRelease(_data.services);
        return _userAcc.requestResourceUpdate(_username,_limits);
    }).then(function(){
        res.send(true);
    }).catch(function(err){
        res.status(400);
        res.send(err.message);
    });
});

router.post('/updateComp',function(req, res, next){
    var _data =  req.body;
    var _username = req.username;

    var _limits = _getlimitsUpdate(_data.addservices,_data.delservices);
    _userAcc.checkAccountBalance(_username,_limits).then(function(){
        return _k8s_adp.getK8s('default');
    }).then(function(_k8s){
        return _k8s.updateCompose(_username,_data);
    }).then(function(){
        return _userAcc.requestResourceUpdate(_username,_limits);
    }).then(function(){
        res.send(true);
    }).catch(function(err){
        res.status(400);
        res.send(err.message);
    });

});

router.post('/getCompAndSt',function(req, res, next){

    var _username = req.username;

    compMetaInfoDB.getWithParam(null,{"username":_username},function(err,rets){
        if(err){
            res.status(400);
            res.send(err.message);
        }else{

            var promises = [];
            rets.forEach(function(item){
                promises.push(_getPodSt(item));
            });

            Promise.all(promises).then(function (retlst) {
                res.send(retlst);
            });
        }
    });

    function _getPodSt(item){
        return  new Promise(function (resolve, reject) {

            _k8s_adp.getK8s('default').then(function(_k8s){
                return _k8s.getPodsWithComposeName(_username,"composeName="+item.id);
            }).then(function(ret){
                item.status = "normal";
                var _json = JSON.parse(ret);
                for(var _i=0;_i<_json.items.length;_i++){
                    if(_json.items[_i].status.phase != "Running"){
                        item.status = 'compose unnormal';
                        break;
                    }
                }
                resolve(item);
            }).catch(function(e){
                item.status = 'exception';
                resolve(item);

            });
        });
    }

});

router.post('/getCompMarket',function(req, res, next){

    var _data =  req.body;
    var _cond = {
        label:'composemarket'
    };

    if(_data.composeId != undefined)
        _cond.id = _data.composeId;

    compMetaInfoDB.getWithParam(null, _cond, function (err,rets) {
        if (err) {
            res.status(400);
            res.send(err.message);
        } else {
            res.send(rets);
        }
    });

});

module.exports = router;